use std::io::Error;
use std::rc::Rc;
use std::time::Duration;
use reqwest;
use serde::Serialize;
use tokio::fs::File;
use tokio::io::{AsyncReadExt, AsyncWriteExt, BufReader, BufWriter};
use futures_util::StreamExt;
use crate::lerror::LipoError;
use crate::ltools::ltime;
use crate::ltools::lmaths;


const TIMEOUT_SPACE:u64 = 10;

pub(crate) async fn send_get<T: Serialize>(url:&str, param:Option<T>){
    let client = reqwest::Client::new();
    let mut request_builder = client.get(url)
        .timeout(Duration::from_secs(TIMEOUT_SPACE));

    // let request_builder = request_builder.header("","");
    // for _ in 0..3 {
    //     request_builder = request_builder.header("","");
    // };
    //
    if let Some(p) = param {
        request_builder = request_builder.query(&p);
    };

    let resp = request_builder.send().await.unwrap();
   match resp.text().await {
       Ok(back_data) => {
            println!("返回数据为： {}", back_data);
       }
       Err(_) => {

       }
   }
}


pub(crate) async fn send_post<T: Serialize>(url:&str, param:Option<T>){

    let start_time = ltime::get_now_millis();
    let client = reqwest::Client::new();
    let mut request_builder = client.post(url)
        .timeout(Duration::from_secs(TIMEOUT_SPACE));

    // let request_builder = request_builder.header("","");
    // for _ in 0..3 {
    //     request_builder = request_builder.header("","");
    // };
    //
    request_builder = request_builder.header("sign_up_token","FCzimPfa1jWCrmR9");
    if let Some(p) = param {
        request_builder = request_builder.json(&p);
    };
    let resp = request_builder.send().await.unwrap();

    match resp.text().await {
        Ok(back_data) => {
            // println!("返回数据为： {}", back_data);
        }
        Err(e) => {
            // println!("输出失败：{:?}",e);
        }
    }
    println!("请求时间差： {}", ltime::get_now_millis() - start_time);
}

/* 下載文件 */
pub(crate) async  fn download_file(url:&str, adr:&str, f:fn(f64)) -> Result<(), LipoError> {
    let start_time = ltime::get_now_millis();
    let client = reqwest::Client::new();
    let mut request_builder = client.get(url)
        .timeout(Duration::from_secs(TIMEOUT_SPACE));

    // 下载文件
    let  file = match File::create(adr).await {
        Ok(f) => {f}
        Err(_) => {return Err(LipoError::FileNoExit)}
    };
    let mut write_buf = BufWriter::new(file);

    let resp = request_builder.send().await.unwrap();
    let total = resp.content_length();
    let mut bytes_steam = resp.bytes_stream();
    let mut downloaded = 0;

    while let Some(item) = bytes_steam.next().await {
        match item {
            Ok(chunk) => {
                downloaded += chunk.len();
                write_buf.write(chunk.iter().as_slice()).await.expect("");
                // println!("total: {:?}, download: {}", total, downloaded);
                if let Some(t) = total {
                    let pro = downloaded as f64 / t as f64;
                    f(lmaths::round_num(pro, 3));
                }
            },
            Err(_e) => {
                return Err(LipoError::HttpDownloadDataError);
            }
        }
    }

    if let Err(_) = write_buf.flush().await {
        return Err(LipoError::IoFlushError);
    }

    Ok(())
}


#[derive(Serialize)]
pub(crate) struct  BaseParam{

}


